<template>
    <el-dialog
        v-model="dialogRef.visible"
        :title="dialogRef.title"
        destroy-on-close
        append-to-body
        width="1000px"
        @close="closeDialogCallback"
        top="5vh"
    >
        <el-form
            ref="menuFormRef"
            :model="formDataRef"
            :rules="rules"
            label-width="160px"
        >
            <el-form-item label="父级菜单" prop="parentId">
                <el-tree-select
                    v-model="formDataRef.parentId"
                    placeholder="选择上级菜单"
                    :data="menuOptions"
                    filterable
                    check-strictly
                    :render-after-expand="false"
                />
            </el-form-item>

            <el-form-item label="菜单名称" prop="name">
                <el-input
                    v-model="formDataRef.name"
                    placeholder="请输入菜单名称"
                />
            </el-form-item>

            <el-form-item label="菜单类型" prop="type">
                <el-radio-group
                    v-model="formDataRef.type"
                    @change="onMenuTypeChange"
                >
                    <el-radio label="CATALOG">目录</el-radio>
                    <el-radio label="MENU">菜单</el-radio>
                    <el-radio label="BUTTON">按钮</el-radio>
                    <el-radio label="EXTLINK">外链</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item
                v-if="formDataRef.type == 'EXTLINK'"
                label="外链地址"
                prop="path"
            >
                <el-input
                    v-model="formDataRef.path"
                    placeholder="请输入外链完整路径"
                />
            </el-form-item>

            <el-form-item
                v-if="
                    formDataRef.type == MenuTypeEnum.CATALOG ||
                    formDataRef.type == MenuTypeEnum.MENU
                "
                label="路由路径"
                prop="path"
            >
                <el-input
                    v-if="formDataRef.type == MenuTypeEnum.CATALOG"
                    v-model="formDataRef.path"
                    placeholder="system"
                />
                <el-input v-else v-model="formDataRef.path" placeholder="user" />
            </el-form-item>

            <!-- 组件页面完整路径 -->
            <el-form-item
                v-if="formDataRef.type == MenuTypeEnum.MENU"
                label="页面路径"
                prop="component"
            >
                <el-input
                    v-model="formDataRef.component"
                    placeholder="system/user/index"
                    style="width: 95%"
                >
                    <template v-if="formDataRef.type == MenuTypeEnum.MENU" #prepend
                        >src/views/</template
                    >
                    <template v-if="formDataRef.type == MenuTypeEnum.MENU" #append
                        >.vue</template
                    >
                </el-input>
            </el-form-item>

            <el-form-item
                v-if="formDataRef.type !== MenuTypeEnum.BUTTON"
                prop="visible"
                label="显示状态"
            >
                <el-radio-group v-model="formDataRef.visible">
                    <el-radio :label="1">显示</el-radio>
                    <el-radio :label="0">隐藏</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item
                v-if="formDataRef.type === MenuTypeEnum.CATALOG"
                label="根目录始终显示"
            >
                <template #label>
                    <div style="vertical-align: middle;">
                        根目录始终显示
                        <el-tooltip placement="bottom" effect="light">
                            <template #content
                                >是：根目录只有一个子路由显示目录
                                <br />否：根目录只有一个子路由不显示目录，只显示子路由
                            </template>
                            <el-icon-questionfilled class="inline-block"  style="width: 1em; height: 1em; margin-right: 3px;"/>
                        </el-tooltip>
                    </div>
                </template>

                <el-radio-group v-model="formDataRef.alwaysShow">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item
                v-if="formDataRef.type === MenuTypeEnum.MENU"
                label="是否缓存"
            >
                <el-radio-group v-model="formDataRef.keepAlive">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="排序" prop="sort">
                <el-input-number
                    v-model="formDataRef.sort"
                    style="width: 100px"
                    controls-position="right"
                    :min="0"
                />
            </el-form-item>

            <!-- 权限标识 -->
            <el-form-item
                v-if="formDataRef.type == MenuTypeEnum.BUTTON"
                label="权限标识"
                prop="perm"
            >
                <el-input v-model="formDataRef.perm" placeholder="sys:user:add" />
            </el-form-item>

            <el-form-item
                v-if="formDataRef.type !== MenuTypeEnum.BUTTON"
                label="图标"
                prop="icon"
            >
                <!-- 图标选择器 -->
                <IconSelect v-model="formDataRef.icon" />
            </el-form-item>

            <el-form-item
                v-if="formDataRef.type == MenuTypeEnum.CATALOG"
                label="跳转路由"
            >
                <el-input v-model="formDataRef.redirect" placeholder="跳转路由" />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="closeDialog">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { TypeMenuFormI } from "@/api/menu/menu_types";
import { MenuTypeEnum } from "@/enums/MenuTypeEnum.ts";
import { reactive, ref } from "vue";
import * as menuApi from '@/api/menu/menu_api_index'
import { ElMessage, FormInstance } from "element-plus";
import {$bus} from '@/event_bus/event_bus_index.ts'
import IconSelect from '@/components/icon_select/icon_select_index.vue'
////#region defineXxx
//defineOptions({
//name:
//});

//const props=defineProps({
//propA:{
//type:String,
//required:true
//},
//propB:{
//type:Number,
//default:1
//},
//propC:{
//type:String as PropType<MyType>,
//required:true
//},
//});

//const emit = defineEmits<{
//event1:[para1:number,para2:string],
//event2:[para1:number,para2:string],
//}>();
////#endregion

const dialogRef = ref({
    title: "",
    visible: false,
});

const menuOptions = ref<TypeOptionI[]>([]);

const formDataInit: TypeMenuFormI = {
    parentId: 0,
    visible: 1,
    sort: 1,
    type: MenuTypeEnum.MENU,
    alwaysShow: 0,
    keepAlive: 0,
};

const formDataRef = ref<TypeMenuFormI>(Object.assign({},formDataInit));
const menuCacheDataRef = ref({
  type: "",
  path: "",
});
const menuFormRef=ref<FormInstance>()

/**
 * 打开表单弹窗
 *
 * @param parentId 父菜单ID
 * @param menuId 菜单ID
 */
 function openDialog(parentId?: number, menuId?: number) {
    menuApi.getMenuOptions()
    .then(({ data }) => {
      menuOptions.value = [{ value: 0, label: "顶级菜单", children: data }];
    })
    .then(() => {
      dialogRef.value.visible = true;
      if (menuId) {
        dialogRef.value.title = "编辑菜单";
        menuApi.getMenuForm(menuId).then(({ data }) => {
          Object.assign(formDataRef.value, data);
          menuCacheDataRef.value.type = data.type;
          menuCacheDataRef.value.path = data.path ?? "";
        });
      } else {
        dialogRef.value.title = "新增菜单";
        formDataRef.value.parentId = parentId;
      }
    });
}

/** 菜单类型切换事件处理,是否生效 */
function onMenuTypeChange() {
  // 如果菜单类型改变，清空路由路径；未改变在切换后还原路由路径
  if (formDataRef.value.type !== menuCacheDataRef.value.type) {
    formDataRef.value.path = "";
  } else {
    formDataRef.value.path = menuCacheDataRef.value.path;
  }
}

/** 菜单保存提交 */
function submitForm() {
  menuFormRef.value?.validate((isValid: boolean) => {
    if (isValid) {
      const menuId = formDataRef.value.id;
      if (menuId) {
        menuApi.updateMenu(menuId, formDataRef.value).then(() => {
          ElMessage.success("修改成功");
          dialogRef.value.visible = false;;
          $bus.emit('menu-table-query');
        });
      } else {
        menuApi.addMenu(formDataRef.value).then(() => {
          ElMessage.success("新增成功");
          dialogRef.value.visible = false;;
          $bus.emit('menu-table-query');
        });
      }
    }
  });
}

function closeDialog(){
    dialogRef.value.visible = false;
}


/** 关闭弹窗 */
function closeDialogCallback() {
  resetForm();
}

/** 重置表单 */
function resetForm() {
  menuFormRef.value?.resetFields();
  menuFormRef.value?.clearValidate();

  formDataRef.value.id = undefined;
  formDataRef.value.parentId = 0;
  formDataRef.value.visible = 1;
  formDataRef.value.sort = 1;
  formDataRef.value.perm = undefined;
  formDataRef.value.component = undefined;
  formDataRef.value.path = undefined;
  formDataRef.value.redirect = undefined;
  formDataRef.value.alwaysShow = undefined;
  formDataRef.value.keepAlive = undefined;
}

const rules = reactive({
  parentId: [{ required: true, message: "请选择顶级菜单", trigger: "blur" }],
  name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择菜单类型", trigger: "blur" }],
  path: [{ required: true, message: "请输入路由路径", trigger: "blur" }],

  component: [{ required: true, message: "请输入组件路径", trigger: "blur" }],
  visible: [{ required: true, message: "请输入路由路径", trigger: "blur" }],
});


defineExpose({
    openDialog,
})
</script>
<style lang="scss" scoped></style>
